package com.maike.babyname.network;


import android.text.TextUtils;

import com.maike.babyname.utils.LogUtils;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 不带带身份校验的okhttp拦截器
 */

public class LogInterceptor implements Interceptor {
    // private String cookie = null;
    private Headers.Builder headerBuilder;

    @Override
    public Response intercept(Chain chain) throws IOException {
        //请求
        Request.Builder builder = chain.request().newBuilder();
        setRequestHeader();
        Request newrequest = builder.headers(headerBuilder.build())
                .build();
        Logger.e("-->header内容" + newrequest.headers().toString());

        LogUtils.Http(String.format("-->: %s", newrequest.url()));
        //响应

        Response response = chain.proceed(newrequest);


        //body log输出
        if (LogUtils.ENABLE) {
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Logger.e("<---------- " + buffer.clone().readString(Charset.forName("UTF-8")));
        }
        return response;
    }

    /**
     * 添加request请求头部
     *
     * @param
     * @return
     */
    private void setRequestHeader() {
//        String tokenStr = SPHelper.getInstance().getStringShareData("token", "");
//        if (!TextUtils.isEmpty(tokenStr)) {
//            headerBuilder = new Headers.Builder()
//                    .add("Content-Type", "application/json;charset=UTF-8")
//                    .add("token", tokenStr);
//        } else {
        headerBuilder = new Headers.Builder()
                .add("Content-Type", "application/json;charset=UTF-8");
//        }
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}